package com.server.common.listener;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.server.common.base.SessionData;
import com.server.service.impl.UserManagementService;

public class SessionListener implements HttpSessionAttributeListener,HttpSessionListener {
	
	private static Map<String, String> uuidUser = new HashMap<String, String>();
	
	public static Map<String, String> getUuidUser() {
		return uuidUser;
	}
	
	public static void setUuidUser(Map<String, String> uuidUser) {
		SessionListener.uuidUser = uuidUser;
	}

	@Override
	public void attributeAdded(HttpSessionBindingEvent event) {
		HttpSession session = event.getSession();
		Object userName = session.getAttribute(SessionData.nameKey);
		Object userUuid = session.getAttribute(SessionData.uuidKey);
		if (userName != null && userUuid != null) {
			uuidUser.put(userUuid.toString(), userName.toString());
		}
		//System.out.println("添加："+DateUtil.getDateStr(new Date(), DateType.YYYY_MM_DD_HH_mm_ss));
		
	}

	@Override
	public void attributeRemoved(HttpSessionBindingEvent event) {
		// TODO Auto-generated method stub
	}

	@Override
	public void attributeReplaced(HttpSessionBindingEvent event) {
		// TODO Auto-generated method stub
	}

	@Override
	public void sessionCreated(HttpSessionEvent event) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void sessionDestroyed(HttpSessionEvent event) {
		HttpSession session = event.getSession();
		Object userName = session.getAttribute(SessionData.nameKey);
		Object userUuid = session.getAttribute(SessionData.loginUuidKey);
		if (userName != null && userUuid != null) {
			uuidUser.remove(userUuid);
			UserManagementService userManagementService = (UserManagementService)this.getObjectFromApplication(session.getServletContext(), "UserManagementService"); 
			//登出记录
			userManagementService.logout(userName.toString(), userUuid.toString());
		}
		//System.out.println("结束："+DateUtil.getDateStr(new Date(), DateType.YYYY_MM_DD_HH_mm_ss));
	}
	private Object getObjectFromApplication(ServletContext servletContext,String beanName){  
        //通过WebApplicationContextUtils 得到Spring容器的实例。  
        ApplicationContext application=WebApplicationContextUtils.getWebApplicationContext(servletContext);  
        //返回Bean的实例。  
        return application.getBean(beanName);  
    } 

}
